package com.devcon5.StudentPlanner;

import baseclasses.Assignment;
import baseclasses.Course;
import baseclasses.Grade;
import database.AssignmentDAO;
import database.GradeDAO;
import forms.GradeForm;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class AddGrade extends GradeForm {
	//Initialize basic variables
	private Assignment assignment;
	private int assignmentId;

	private AlertDialog alert;
	private boolean courseSelected;

	public static final String COURSE_SELECTED = "COURSE_SELECTED";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(savedInstanceState!=null)	//if there was an activity called in front or orientation change, set display to saved state of selected course
		{
			courseSelected = savedInstanceState.getBoolean(COURSE_SELECTED);
		}

		try{
			assignmentId = getIntent().getExtras().getInt( Assignment.ASSIGNMENT_ID );	//unpackage assignment ID from extras passed by AddGrade option in ViewAssignments class
			assignment = AssignmentDAO.getAssignmentById( AddGrade.this , assignmentId);	//get the assignment object for this context (addgrade.java) from db
			assignmentId = assignment.getId();	//get the assignment ID
		}
		catch(java.lang.NullPointerException e){
			assignmentId = -1;
		}


		
		if(assignmentId==-1){	//if the assignment's ID is unset (there's no assignment attached to this grade)
			if(courses.size()>1 && !courseSelected){	//if there are courses available & noen are selected
				if(alert==null)	//if the alert dialog hasn't been instantiated, create it and show it
					alert = createCourseAlertDialog();
				alert.show();
			}
		}
		//set text views to the correct  information
		else{
			courseTitle.setText(assignment.getName()+""); //TO DO change to gradeTitle--not courseTitle
			courseSpinner.setSelection(getCoursePosition(assignment.getCourseId()));	//get the course view associated
			scoreEditText.requestFocus();	//give the score focus
		}

	}

	@Override
	protected void onPause() {	//dismiss the alert dialog
		if(alert!=null)
			alert.dismiss();
		super.onPause();
	}


	public AlertDialog createCourseAlertDialog(){	//create an alert dialog containing courses to choose from to associate grade with
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Course");
		builder.setIcon(R.drawable.check);
		CharSequence[] courseStrings = new CharSequence[courses.size()];
		for(int i=0;i<courses.size();i++){
			courseStrings[i] = courses.get(i).getName();
		}
		builder.setItems(courseStrings, new DialogInterface.OnClickListener() {

	
			public void onClick(DialogInterface dialog, int which) {
				courseSpinner.setSelection(which);
				courseSelected = true;
			}
		});
		AlertDialog alert = builder.create();
		return alert;
	}

	public int getCoursePosition(int courseId){	//get the selected course position, and return the ID of the selected course
		for(int i=0;i<courses.size();i++){
			if(courses.get(i).getId()==courseId){
				return i;
			}
		}
		return 0;
	}

	@Override
	public void addButtonClicked() {	//get the grade name, if the name is there and the course ID
		String title = courseTitle.getText().toString();
		if(title.length()>0){
			int courseId = ((Course)courseSpinner.getSelectedItem()).getId();
			try{	//parse the score values and add the grade by assignment ID and course ID
				double score = Double.parseDouble(scoreEditText.getText().toString());
				double outOf = Double.parseDouble(outOfEditText.getText().toString());
				Grade grade = new Grade(title, assignmentId, courseId, score, outOf);
				GradeDAO.addGrade(AddGrade.this, grade);
				
				
				
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( this ); //check the prefs
				boolean comepleteGraded = prefs.getBoolean("completegradedpref", true);	//if prefs say mark completed when grade entered, do so
				
				if( comepleteGraded )
				{
					markAssignmentComplete( assignmentId );
				}
				
				
				onBackPressed();
				finish();
			}
			catch(NumberFormatException e){	//invalid score and points
				Toast.makeText(AddGrade.this, "Score and total points must be valid!", Toast.LENGTH_SHORT).show();
			}
		}
		else{	//grade name can't be blank
			Toast.makeText(AddGrade.this, "Grade title cannot be blank!", Toast.LENGTH_SHORT).show();
		}
		super.addButtonClicked();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {	//bundle the selected course

		outState.putBoolean(COURSE_SELECTED, courseSelected);

		super.onSaveInstanceState(outState);
	}
	
	public void markAssignmentComplete( int assignmentId )
	{
		if( assignmentId == -1)	//no assignment, do nothing
		{
			return;
		}
		
		AssignmentDAO.getAssignmentById( this, assignmentId );
		
		if( !assignment.isCompleted() )	//if assignment isnt marked complete, do so
		{
			assignment.setCompleted( true );
			AssignmentDAO.markAssigment(this, assignment);
		}
	}


}
